#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>

//UDP server
#define IP  "127.0.0.1"
#define SPORT 60000
#define SIZE  100

int socketInit(const char * ip, unsigned short port);

int main()
{
	int socketID = 0;
	ssize_t ret = 0;
	char buffer[SIZE] = {0};
	int addrLength = 0;
	struct sockaddr_in addr;
	
	socketID = socketInit("127.0.0.1", 60000);
	//等待数据（接收消息）
	addrLength = sizeof(addr);
	ret = recvfrom(socketID, buffer, SIZE - 1, 0, (struct sockaddr *)&addr, &addrLength);
	if ( 0 > ret )
	{
		perror("recvfrom error");
	}
	else 
	{
		//处理消息
		printf("server get data:%s, from port:%d\r\n", buffer, ntohs(addr.sin_port));
	}
	
	//作出回应
	fgets(buffer, SIZE - 1, stdin);	
	ret = sendto(socketID, buffer, strlen(buffer), 0, (struct sockaddr *)&addr, addrLength);
	if ( 0 > ret )
	{
		perror("server send message error");
	}
	else 
	{
		printf("服务器回复客户端：%s\r\n", buffer);
	}
	//关闭socket
	close(socketID);
	return 0;
}

int socketInit(const char * ip, unsigned short port)
{
	int socketID = 0;
	int on = 1;
	
	//创建socket 
	socketID = socket( PF_INET, SOCK_DGRAM, 0 );
	if ( 0 > socketID )
	{
		perror("socket error");
		exit(0);
	}
	printf("socket ok\r\n");
	
	if (0 > setsockopt(socketID, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)))
	{
		perror("set sock opt reUseAddr error");
	}
	
	//绑定自己的ip+port
	struct sockaddr_in addr = {
		.sin_family = PF_INET,
		.sin_port   = htons(port),
		.sin_addr   = {
			.s_addr = INADDR_ANY,
		},
	};
	if ( 0 > bind(socketID, (struct sockaddr *)&addr, sizeof(addr)))
	{
		perror("bind error");
		exit(0);
	}
	printf("bind ok\r\n");
	return socketID;
}